<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Titbit Upload</title>
  <link rel="stylesheet" href="/static/css/concise.min.css">
  <link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
  <div container>
    
    <div style="margin-top: 1rem;"></div>

    <div grid>

      <div column></div>

      <div column='10'>
        
        <form onsubmit="return false;">
          <!--name="image" 服务端接收到数据，标记的上传名就是image-->
          <input type="file" name="image" onchange="uploadImage(this);">
        </form>
        <div id="image-show"></div>
      </div>

      <div column></div>

    </div>
  </div>

  <script>
    let host = `${location.protocol}//${location.host}`

    function uploadImage (t) {
      if (t.files.length <= 0) {
        return false;
      }

      let fm = new FormData()

      /* for (let f of t.files) {
        fm.append('image', f)
      } */

      fm.append('image', t.files[0]);
      
      fetch(`${host}/image`, {
        method : 'POST',
        body: fm
      })
      .then(res => {
        if (res.ok) {
          return res.text();
        }
      })
      .then(name => {
        document.getElementById('image-show').innerHTML = 
          `<img src="${host}/image/${name}" style="width:100%;height:auto;">`;
      })
      .catch (err => {
        document.getElementById('image-show').innerHTML = err.message;
      });

    }

  </script>

</body>
</html>